'''
Created on Nov 4, 2009

@author: wangjo
'''
import os
import re
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.api import mail
from google.appengine.ext.webapp import template
import logging
import mokomodel

DEBUG = True
DEFAULT_LIMIT = 24
CACHE_DURATION = 60*60*24
CACHE_NS_GALLERY_WEB ='list_web' 
CACHE_NS_GALLERY_IPHONE = 'list_iphone'
CACHE_NS_MODEL = 'topgirl'
CACHE_NS_ALBUM = 'gallery'
CACHE_NS_CATEGORYLIST = 'categorylist'
CACHE_NS_CATEGORY = 'category'

template.register_template_library('templatefilters')

class BaseRequestHandler(webapp.RequestHandler):
    HOST_IMG = 'http://www.m.mywhere.org/mtg/moko'
    HOST_THUMB = 'http://www.m.mywhere.org/mtg/150'
    HOST_THUMB80 = 'http://www.m.mywhere.org/mtg/80'
    HOST_THUMB480 = 'http://www.m.mywhere.org/mtg/480'
    def rssgenerate(self, template_name, template_values = {}):
        self.response.headers['Content-Type'] = 'application/rss+xml'
        self.generate(template_name, template_values, detectmb = False)
        
    def generate(self, template_name, template_values = {}, detectmb = True):
        imghost = mokomodel.setting.get_setting('host_image')
        if not imghost:
            imghost = self.HOST_IMG
        thumbhost150 = mokomodel.setting.get_setting('host_thumb')
        if not thumbhost150:
            thumbhost150 = self.HOST_THUMB
        thumbhost80 = mokomodel.setting.get_setting('host_thumb80')
        if not thumbhost80:
            thumbhost80 = self.HOST_THUMB80
        thumbhost = thumbhost150
        thumbhost480 = self.HOST_THUMB480
        if template_values.has_key('thumb') and template_values['thumb'] == 80:
            thumbhost = thumbhost80
        logging.info('base output method')
        values = {
            'request' : self.request,
            'host_img': imghost,
            'host_thumb480':thumbhost480,
            'host_thumb': thumbhost,
            'user' : users.get_current_user(),
            'is_admin': users.is_current_user_admin(),
            'login_url': users.create_login_url(self.request.uri),
            'logout_url': users.create_logout_url('http://%s/' % (self.request.host,)),
            'debug' : self.request.get('deb'),
            'application_name' : 'MOKO Top Girl',
        }
        logging.info('user-agent:%s'%self.request.headers['User-Agent'])
        values.update(template_values)
        dir = os.path.dirname(__file__)
        if detectmb:
            mobile = self.detectBrowser()
            if mobile != '':
                splits = template_name.split('.')
                splits.insert(1, mobile)
                new_template_name = u'.'.join(splits)
                mobile_path = os.path.join(dir, os.path.join('templates', new_template_name))
                if os.path.exists(mobile_path):
                    template_name = new_template_name
        path = os.path.join(dir, os.path.join('templates', template_name)) 
        self.response.out.write(template.render(path, values))
        
    def pageHandler(self):
        page = self.request.get('page', None)
        if not page or int(page) < 1:
            page = 1
        else:
            page = int(page)
        return page
    
    def limitHandler(self):
        limit = self.request.get('limit', None)
        if not limit or int(limit) < 1:
            limit = DEFAULT_LIMIT
        else:
            limit = int(limit)
        logging.debug('limit: %d'%limit)
        return limit
    
    def thumbHandler(self):
        thumb = self.request.get('thumb', None)
        if not thumb or int(thumb) == 150:
            thumb = 150
        else:
            thumb = 80
        return thumb
    
    def detectBrowser(self):
        type = ''
        
        useragent = self.request.headers['User-Agent']
        if useragent:
            ug = useragent.lower()
            if ug.find('iphone') >= 0 or ug.find('ipod')>=0:
                type = 'iphone'
            elif ug.find('android')>=0:
                type = 'android'
            elif ug.find('blackberry') >= 0:
                type = 'blackberry'
            elif re.search('(palm os|palm|hiptop|avantgo|plucker|xiino|blazer|elaine)', ug):
                type = 'palm'

        return type
    
class MultipleOutputRequestHandler(BaseRequestHandler):
    _OUTPUT_TYPES = {
            'default': ['text/html', 'html'],
            'html': ['text/html', 'html'],
            'atom': ['application/atom+xml', 'xml'],
            'json': ['application/javascript', 'json'],
            }
    def multiplegen(self, template_name, template_values = {}):
        logging.info('multip output method')
        output_name = self.request.get('output')
        logging.info('output:%s'%output_name)
        if output_name not in self._OUTPUT_TYPES:
            output_name = 'default'
        logging.info('output: %s'%output_name)
        output_type = self._OUTPUT_TYPES[output_name]
        self.response.headers['Content-Type'] = output_type[0]
        template_name = '%s.%s' % (template_name, output_type[1])
        self.generate(template_name, template_values, detectmb = False)
   
def sendmail(title, message):
    message = mail.EmailMessage(sender="MTopGirl <support@mtopgirl.appspot.com>", subject=title)
    message.to = "John Wang <yongtao.wang@gmail.com>"
    message.body = message

    message.send()     